package com.swak.fx.support;

import java.util.List;
import java.util.Map;

import com.swak.utils.Lists;
import com.swak.utils.Maps;

/**
 * 存储
 * 
 * @author 618lf
 */
public class Store {

	private static Store ME = new Store();

	public static Store New() {
		return ME;
	}

	private Store() {
	}

	private Map<String, Object> cache = Maps.newConcurrentMap();
	private Map<String, List<ChangeListener>> notifiers = Maps.newConcurrentMap();

	public void put(String key, Object value) {
		Object old = cache.put(key, value);
		List<ChangeListener> cls = notifiers.get(key);
		this.fireEvent(cls, old, value);
	}

	public void delete(String key) {
		Object old = cache.remove(key);
		List<ChangeListener> cls = notifiers.get(key);
		this.fireEvent(cls, old, null);
	}

	private void fireEvent(List<ChangeListener> cls, Object o, Object n) {
		if (cls != null) {
			for (ChangeListener cl : cls) {
				cl.change(o, n);
			}
		}
	}

	public Object get(String key) {
		return cache.get(key);
	}

	public void watch(String key, ChangeListener listener) {
		List<ChangeListener> clss = notifiers.computeIfAbsent(key, (k) -> {
			return Lists.newCopyOnWriteArrayList();
		});
		clss.add(listener);
	}

	public void unwatch(String key, ChangeListener listener) {
		List<ChangeListener> clss = notifiers.computeIfAbsent(key, (k) -> {
			return Lists.newCopyOnWriteArrayList();
		});
		clss.remove(listener);
	}

	@FunctionalInterface
	public static interface ChangeListener {
		void change(Object o, Object n);
	}
}
